﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
using Microsoft.Office.Interop.Outlook;
using OutlookMGI.Logica;
using ComunesMGI.DataTypes;
using ComunesMGI.Mensajes;
using ComunesMGI.Constantes;

namespace OutlookMGI
{
    public partial class ThisAddIn
    {
        Office.CommandBarButton btn1;
        Office.CommandBarButton btn2;
        Office.CommandBarButton button;
        Outlook.Selection selection;
        Outlook.MailItem item;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Outlook.Explorer explorer = this.Application.ActiveExplorer();
            if (explorer != null)
            {
                Office.CommandBar bar = explorer.CommandBars.Add("MGI", 1, missing, true);
                bar.Visible = true;
                btn1 = (Office.CommandBarButton)bar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, true);
                btn1.Caption = "Alta Incidente";
                btn1.Tag = "myOutlookAddin1.btn1";
                btn1.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                btn1.FaceId = 215;
                btn1.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(Btn1_Click);

                btn2 = (Office.CommandBarButton)bar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, missing, true);
                btn2.Caption = "Sincronizar Tareas";
                btn2.Tag = "myOutlookAddin1.btnSync";
                btn2.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                btn2.FaceId = 1759;
                btn2.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(Btn2_Click);

                Application.ItemContextMenuDisplay += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemContextMenuDisplayEventHandler(Application_ItemContextMenuDisplay);
                Application.ContextMenuClose += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ContextMenuCloseEventHandler(Application_ContextMenuClose);
            }
        }

        private void Btn2_Click(Office.CommandBarButton Ctrl, ref bool Cancel)
        {
            if (MessageBox.Show(
                    "Se van a sincronizar sus tareas, ¿está seguro?",
                    "Confirmar sincronización",
                MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                SincronizarTareas();
        }

        private void SincronizarTareas()
        {
            try
            {

                List<DataSincronizarTarea> tareas;
                ILogica il = LogicaFactory.GetInstance().GetILogica();
                tareas = il.SincronizarTareas();
                string filtro = "@SQL=" + Convert.ToChar(34).ToString() + "http://schemas.microsoft.com/mapi/string/";
                filtro += "{00020329-0000-0000-C000-000000000046}/IdMGI";
                filtro += "/0000001F" + Convert.ToChar(34).ToString() + " = ";
                NameSpace ns = this.Application.GetNamespace("MAPI");
                Folder tareasFolder = (Folder)ns.GetDefaultFolder(OlDefaultFolders.olFolderTasks);

                foreach (DataSincronizarTarea tarea in tareas)
                {
                    String identificador = tarea.IdCliente.ToString() + ";" + tarea.IdSistema.ToString() + ";" + tarea.IdTarea.ToString();
                    switch (tarea.EstadoSincronizacion)
                    {

                        case EstadoSincronizacion.Alta:
                            TaskItem taskNueva = (TaskItem)this.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olTaskItem);
                            taskNueva.Subject = tarea.Titulo;
                            taskNueva.PercentComplete = tarea.PorcentajeCompletado;
                            if (tarea.Comienzo != ConstantesMGI.FechaVacia)
                                taskNueva.StartDate = tarea.Comienzo;
                            if (tarea.Vencimiento != ConstantesMGI.FechaVacia)
                                taskNueva.DueDate = tarea.Vencimiento;
                            taskNueva.Body = tarea.Descripcion;
                            taskNueva.UserProperties.Add("IdMGI", OlUserPropertyType.olText, false, 1);
                            taskNueva.UserProperties["IdMGI"].Value = identificador;
                            taskNueva.Save();
                            break;


                        case EstadoSincronizacion.Baja:
                            foreach (TaskItem task in tareasFolder.Items.Restrict(filtro + "'" + identificador + "'"))
                            {
                                task.Delete();
                                // Se supone que hay a lo sumo una
                                break;
                            }
                            break;

                        case EstadoSincronizacion.Modificación:
                            TaskItem taskMod;
                            Items tareasOutlook = tareasFolder.Items.Restrict(filtro + "'" + identificador + "'");
                            if (tareasOutlook.Count == 0)
                            {
                                taskMod = (TaskItem)this.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olTaskItem);
                                taskMod.UserProperties.Add("IdMGI", OlUserPropertyType.olText, false, 1);
                                taskMod.UserProperties["IdMGI"].Value = identificador;
                            }
                            else
                                taskMod = (TaskItem)(tareasOutlook.GetFirst());

                            taskMod.Subject = tarea.Titulo;
                            taskMod.PercentComplete = tarea.PorcentajeCompletado;
                            if (tarea.Comienzo != ConstantesMGI.FechaVacia)
                                taskMod.StartDate = tarea.Comienzo;
                            if (tarea.Vencimiento != ConstantesMGI.FechaVacia)
                                taskMod.DueDate = tarea.Vencimiento;
                            taskMod.Body = tarea.Descripcion;
                            taskMod.Save();
                            break;

                        default:
                            break;
                    }
                }
                MsgNotificacion notif = new MsgNotificacion("Tareas sincronizadas", "Se han sincronizado correctamente sus tareas.", "");
                notif.ShowDialog();

            }
            catch (System.Exception e)
            {
                MsgError err = new MsgError("Error", "Ha ocurrido un error inesperado.", e.Message);
                err.ShowDialog();
            }


        }

        private void Btn1_Click(Office.CommandBarButton Ctrl, ref bool Cancel)
        {
            selection = this.Application.ActiveExplorer().Selection;
            if (GetMessageClass(selection[1]) == "IPM.Note" && selection.Count == 1)
                try
                {
                    item = (Outlook.MailItem)selection[1];
                }
                catch (System.Exception)
                {
                    item = null;
                }

            if (item != null)
            {
                item.Display(false);
                item.GetInspector.SetCurrentFormPage("OutlookMGI.IncidentesGUI");
            }

            selection = null;
            item = null;
        }

        void Application_ContextMenuClose(Microsoft.Office.Interop.Outlook.OlContextMenu ContextMenu)
        {
            selection = null;
            item = null;
            if (button != null)
                button.Click -= new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(Btn1_Click);
            button = null;
        }

        void Application_ItemContextMenuDisplay(Microsoft.Office.Core.CommandBar CommandBar, Microsoft.Office.Interop.Outlook.Selection Selection)
        {
            selection = this.Application.ActiveExplorer().Selection;
            if (GetMessageClass(selection[1]) == "IPM.Note" && selection.Count == 1)
            {
                item = (Outlook.MailItem)selection[1];
                button = (Office.CommandBarButton)CommandBar.Controls.Add(Office.MsoControlType.msoControlButton, missing, missing, 1, missing);
                button.Caption = "Alta Incidente";
                button.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                button.FaceId = 215;
                button.Visible = true;
                button.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(Btn1_Click);
            }
        }

        private string GetMessageClass(object item)
        {
            object[] args = new Object[] { };
            Type t = item.GetType();
            return t.InvokeMember("messageClass",
                System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.GetProperty,
                null,
                item,
                args).ToString();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            Application.ItemContextMenuDisplay -= new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemContextMenuDisplayEventHandler(Application_ItemContextMenuDisplay);
            Application.ContextMenuClose -= new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ContextMenuCloseEventHandler(Application_ContextMenuClose);

        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
